package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.transaction.annotation.Transactional;

import com.sophossystems.client.asmon.dao.TipoPersonaDao;
import com.sophossystems.client.asmon.dto.ActivityDTO;
import com.sophossystems.client.asmon.dto.ActivityPkDTO;
import com.sophossystems.client.asmon.dto.TipoPersonaDTO;
import com.sophossystems.client.asmon.dto.TipoPersonaPkDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;
import com.sophossystems.client.asmon.hibernate.Activity;
import com.sophossystems.client.asmon.hibernate.TipoPersona;

public class TipoPersonaDaoImpl extends AbstractDAO implements TipoPersonaDao
{
	
	private static Logger log = Logger.getLogger(TipoPersonaDaoImpl.class);
	/**
	 * Method 'insert'
	 * 
	 * @param dto
	 * @return ActivityPk
	 */
	
	@Override
	@Transactional
	public TipoPersonaPkDTO insert(final TipoPersonaDTO dto){
		TipoPersonaPkDTO exito =null ;
	try {
		 exito = (TipoPersonaPkDTO) getHibernateTemplate().execute(new HibernateCallback() {
			/**
			 * {@inheritDoc}
			 * 
			 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
			 */
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Transaction tx = session.beginTransaction();
				TipoPersonaPkDTO pk = null;
			    TipoPersona acti = new TipoPersona();
			    acti.mapper(dto);
			    session.save(acti);
			    tx.commit();
			 
			    try {
			    	TipoPersonaPkDTO res = findLastInsert();
					pk = new TipoPersonaPkDTO();
					pk.setIdTipoCliente(res.getIdTipoCliente());
					
					
				} catch (DaoException es) {
					
					throw new HibernateException("Insersion: " +es.getMessage());
				}
				return pk;
			
				
			}

			
		});
	///	 return exito;
	} catch (final Exception e) {
		logger.error("Error: TipoPersona, cause: " + e.getMessage(), e);
		
	}
	return exito;
}

		
	/** 
	 * Updates a single row in the Activity table.
	 */
	@Transactional
	public void update(final ActivityPkDTO pk,final ActivityDTO dto) throws DaoException
	{
		try {
			 getHibernateTemplate().execute(new HibernateCallback() {
				/**
				 * {@inheritDoc}
				 * 
				 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
				 */
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
				    Transaction tx = session.beginTransaction();
				    String hqlUpdate = "UPDATE " + getTableName() + " SET idActivity = :idActivity, Description = :descripcion, idModule = :idModule WHERE idActivity = :actividadId";
	                logger.info("Se inserta en: "+getTableName());
				    session.createQuery(hqlUpdate).setInteger("idActivity", dto.getIdActivity()).setString("descripcion", dto.getDescription()).setInteger("idModule",dto.getIdModule()).setInteger("actividadId",pk.getIdActivity()).executeUpdate();
					tx.commit();
					return null;
				}		
			});
		} catch (final Exception e) {
			logger.error("Error: getActivity, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getActivity, cause: " + e.getMessage());
		}
	
		
	
	}

	/** 
	 * Deletes a single row in the Activity table.
	 */

	@Transactional
	public void delete(final ActivityPkDTO pk) throws DaoException
	{
		
		
		try {
			 getHibernateTemplate().execute(new HibernateCallback() {
				/**
				 * {@inheritDoc}
				 * 
				 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
				 */
				@Override
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
				    Transaction tx = session.beginTransaction();
				    Activity activity = (Activity)session.load(Activity.class,pk.getIdActivity() );
				    session.delete(activity);
					tx.commit();
					return null;
				}		
			});
		} catch (final Exception e) {
			logger.error("Error: getActivity, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getActivity, cause: " + e.getMessage());
		}
	}
	

	/**
	 * Method 'getTableName'
	 * 
	 * @return String
	 */
	public String getTableName()
	{
		return "TIPO_PERSONA";
	}

	/** 
	 * Returns all rows from the TIPO_PERSONA table that match the criteria 'idTipoCliente = :idTipoCliente'.
	 */

	@Override
	@Transactional
	public TipoPersonaDTO findByPrimaryKey(final int idTipoCliente) throws DaoException
	{
		TipoPersonaDTO cliente = null;
		try {
			cliente = (TipoPersonaDTO) getHibernateTemplate().execute(
					new HibernateCallback() {

						@Override
						public Object doInHibernate(final Session session)
								throws HibernateException, SQLException {
							
							final Query oQuery = session
									.createQuery("SELECT t.idTipoCliente as idTipoCliente, t.descripcion as descripcion FROM " 
							+ getTableName() + " t WHERE t.idTipoCliente = :idTipoCliente");

							oQuery.setInteger("idTipoCliente", idTipoCliente);

							final TipoPersonaDTO tipoDTO = (TipoPersonaDTO) oQuery
									.setResultTransformer(Transformers
											.aliasToBean(TipoPersonaDTO.class)).list();
							return tipoDTO;
						}
					});

			
		} catch (final Exception e) {
			logger.error("Error: getCliente, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getCliente, cause: "
					+ e.getMessage());
		}
		return cliente;
		
	}

	/** 
	 * Returns all rows from the TIPO_PERSONA table that match the criteria ''.
	 */
	@Override
	@Transactional
	@SuppressWarnings("unchecked")
	public List<TipoPersonaDTO> findAll() throws DaoException
	{
		List<TipoPersonaDTO> actividad = null;
		try {
			actividad= (List<TipoPersonaDTO>)getHibernateTemplate().execute(new HibernateCallback() {
				/**
				 * {@inheritDoc}
				 * 
				 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
				 */
				@Override
				
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					final Query oQuery = session
					.createQuery("SELECT t.idTipoCliente as idTipoCliente, t.descripcion as descripcion FROM " 
					+ getTableName() + " t ORDER BY t.idTipoCliente");
					List<TipoPersonaDTO> actividaddto = (List<TipoPersonaDTO>) oQuery
					.setResultTransformer(
							Transformers
									.aliasToBean(TipoPersonaDTO.class));

					return actividaddto;
				}		
			});
		} catch (final Exception e) {
			logger.error("Error: getActivity, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getActivity, cause: " + e.getMessage());
		}
		return actividad;
		/*
		try {
			return jdbcTemplate.query("SELECT idTipoCliente, descripcion FROM " + getTableName() + " ORDER BY idTipoCliente", this);
		}
		catch (Exception e) {
			logger.error("Error: TipoPersona, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}*/
		
	}

	/** 
	 * Returns all rows from the TIPO_PERSONA table that match the criteria 'idTipoCliente = :idTipoCliente'.
	 */
	@Override
	@Transactional
	public List<TipoPersonaDTO> findWhereIdTipoClienteEquals(int idTipoCliente) throws DaoException
	{
		
		/*try {
			return jdbcTemplate.query("SELECT idTipoCliente, descripcion FROM " + getTableName() + " WHERE idTipoCliente = ? ORDER BY idTipoCliente", this,idTipoCliente);
		}
		catch (Exception e) {
			logger.error("Error: TipoPersona, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}*/
		return null;
	}

	/** 
	 * Returns all rows from the TIPO_PERSONA table that match the criteria 'descripcion = :descripcion'.
	 */
	@Override
	@Transactional
	@SuppressWarnings("unchecked")
	public List<TipoPersonaDTO> findWhereDescripcionEquals(final String descripcion) throws DaoException
	{
		
		
		List<TipoPersonaDTO> actividad = null;
		try {
			actividad= (List<TipoPersonaDTO>)getHibernateTemplate().execute(new HibernateCallback() {
				/**
				 * {@inheritDoc}
				 * 
				 * @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
				 */
				@Override
				
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					final Query oQuery = session
					.createQuery("SELECT t.idTipoCliente as idTipoCliente, t.descripcion as descripcion FROM "
					+ getTableName() + " t WHERE t.descripcion = :descripcion ORDER BY descripcion");
					List<TipoPersonaDTO> actividaddto = (List<TipoPersonaDTO>) oQuery.setString("descripcion", descripcion)
					.setResultTransformer(
							Transformers
									.aliasToBean(TipoPersonaDTO.class));

					return actividaddto;
				}		
			});
		} catch (final Exception e) {
			logger.error("Error: getActivity, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getActivity, cause: " + e.getMessage());
		}
		return actividad;
		
		
	}

	/** 
	 * Returns the rows from the TIPO_PERSONA table that matches the specified primary-key value.
	 */
	@Override
	public TipoPersonaDTO findByPrimaryKey(TipoPersonaPkDTO pk) throws DaoException
	{
		return findByPrimaryKey( pk.getIdTipoCliente() );
	}
	
	
	
	/** 
	 * Returns the rows from the TIPO_PERSONA table that matches the specified primary-key value.
	 */
	
	@Override
	public TipoPersonaPkDTO findLastInsert() throws DaoException {
		TipoPersonaPkDTO tipoPersona = null;
		try {
			tipoPersona = (TipoPersonaPkDTO) getHibernateTemplate().execute(
					new HibernateCallback() {

						@Override
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							
							Query oQuery = session
									.createQuery("SELECT max(t.idTipoCliente) as idTipoCliente FROM "
											+ getTableName()
											+ " t ");
							
							TipoPersonaPkDTO tipoPersonaDto = (TipoPersonaPkDTO) oQuery
									.setResultTransformer(Transformers
											.aliasToBean(TipoPersonaPkDTO.class)).list().get(0);
							return tipoPersonaDto;
						}
					});
		
		} catch (Exception e) {
			logger.error("Error: TipoPersonaDaoImpl, cause: " + e.getMessage(), e);
			throw new DaoException("Query failed", e);
		}
		return tipoPersona;

	}
	
	


}
